<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2017 河源市卓锐科技有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

namespace app\common\model;

use AlibabaCloud\Dyplsapi\V20170525\DeleteSecretBlacklist;
use think\Db;
use think\Exception;
use think\Model as ThinkModel;


class ProductOrder extends ThinkModel
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'qt_product_order';
    protected $pk = 'id';
    protected $autoWriteTimestamp = true;

    /**
     * @param $data [提交过来的参数]
     * @param $userInfo [用户信息]
     */
    public function createOrder($data, $userInfo)
    {
        $result = [];
        $goodsRes = json_decode($data['goods'], true);
        if(isset($data['hand_card_name']) && !empty($data['hand_card_name'])){
            $handCardId= Db::name('qt_hand_card')->where(['store_id'=>$userInfo['store_id'],'name'=>$data['hand_card_name']])->value('id');
            if($handCardId == null){
                $result['status'] = false;
                $result['msg'] = '无效的手牌';
                return $result;
            }
            $data['hand_card_id'] = $handCardId;
            //检测最大消费金额
            $checkMoney = HandCard::checkMaxMoney($data['hand_card_id'],$data['total_price']);
            if($checkMoney == false){
                $result['status'] = false;
                $result['msg'] = '手牌超出最大消费';
                return $result;
            }
            //检测停牌
            $checkStatus = HandCard::checkStatus($data['hand_card_id']);
            if($checkStatus == false){
                $result['status'] = false;
                $result['msg'] = '该手牌未发放或者已经停牌';
                return $result;
            }
        }
        if(isset($data['hand_card_id']) && !empty($data['hand_card_id'])){
            $checkMoney = HandCard::checkMaxMoney($data['hand_card_id'],$data['total_price']);
            if($checkMoney == false){
                $result['status'] = false;
                $result['msg'] = '手牌超出最大消费';
                return $result;
            }
            //检测停牌
            $checkStatus = HandCard::checkStatus($data['hand_card_id']);
            if($checkStatus == false){
                $result['status'] = false;
                $result['msg'] = '该手牌已经停牌';
                return $result;
            }
        }
        $goodsOrder = Db::name('qt_product_order')->where(['room_id' => $data['room_id'], 'order_status' => '0'])->find();
        $saleId = !empty($data['engineer_id']) ? $data['engineer_id'] : $userInfo['id'];
        $roomStatus = Db::name('qt_room')->where(['id'=>$data['room_id']])->value('status_id');
        if($roomStatus == '1'){
            //开房间
            Db::name('qt_room')->where(['id'=>$data['room_id']])->update(['status_id'=>'10']);
        }
        if($roomStatus == '5' || $roomStatus == '6' ||$roomStatus == '7'|| $roomStatus == '8'|| $roomStatus == '4'){
            $result['status'] = false;
            $result['msg'] = '房间状态有问题';
            return $result;
        }
        if (empty($goodsOrder)) {
            //创建订单
            $orderInsert = [
                'order_no' => c_order_sn('2'),
                'store_id' => $userInfo['store_id'],
                'room_id' => $data['room_id'],
                'engineer_id' => $data['engineer_id'],
                'create_id' => $userInfo['id'],
                'hand_card_id' => $data['hand_card_id'],
                'total_price' => $data['total_price'],
                'content' => !empty($data['content']) ? $data['content'] : '',
                'order_status' => '0',
                'create_time' => time(),
            ];
            try {
                Db::startTrans();
                $orderId = Db::name('qt_product_order')->insertGetId($orderInsert);
                //插入子订单
                self::saveProductOrderItem($goodsRes, $orderId, $userInfo, $saleId,$data['hand_card_id']);
                //处理提成记录
                self::saveCommissionLog($orderId, $data['room_id']);
                //发送消息
                Db::commit();
                $result['status'] = true;
                $result['order_id'] = $orderId;
            } catch (Exception $exception) {
                Db::rollback();
                $result['status'] = false;
                $result['msg'] = '下单失败:'.$exception->getFile().$exception->getLine().$exception->getMessage();
            }
        } else {
            try {
                Db::startTrans();
                //插入子订单
                $itemStatus = self::saveProductOrderItem($goodsRes, $goodsOrder['id'], $userInfo, $saleId,$data['hand_card_id']);
                if($itemStatus['status'] == false){
                    $result['status'] = false;
                    $result['msg'] = $itemStatus['msg'];
                }else{
                    //处理提成记录
                    self::saveCommissionLog($goodsOrder['id'], $data['room_id']);
                    //更新总订单金额
                    Db::name('qt_product_order')->where('id', $goodsOrder['id'])->setInc('total_price', $data['total_price']);
                    Db::commit();
                    $result['status'] = true;
                    $result['order_id'] = $goodsOrder['id'];
                }

            } catch (Exception $exception) {
                Db::rollback();
                $result['status'] = false;
                $result['msg'] = '下单失败:'.$exception->getFile().$exception->getLine().$exception->getMessage();
            }
        }
        return $result;
    }


    /**
     * 写入子订单
     * @param $goodsRes    提交的商品数组
     * @param $orderId     商品订单ID
     * @param $userInfo    用户详情
     * @param $saleId      技师ID
     */
    public static function saveProductOrderItem($goodsRes, $orderId, $userInfo, $saleId,$handCardId = '')
    {
        $insert = [];
        foreach ($goodsRes as $key => $value) {
            $goods_info = Db::name('qt_goods')->where('id', $value['product_id'])->find();
            $orderData = Db::name('qt_product_order')
                ->field('o.id,o.room_id,o.hand_card_id,hc.type as hand_type')
                ->alias('o')
                ->leftJoin('qt_hand_card hc','hc.id = o.hand_card_id')
                ->where('o.id', $orderId)
                ->find();
            $roomId = $orderData['room_id'];
            $insert[$key]['order_id'] = $orderId;
            $insert[$key]['room_id'] = $roomId;
            $insert[$key]['store_id'] = $userInfo['store_id'];
            $insert[$key]['hand_card_id'] = $handCardId;
            $insert[$key]['goods_id'] = $value['product_id'];
            $insert[$key]['goods_name'] = $value['product_name'];
            $insert[$key]['goods_price'] = $value['product_price'];
            $insert[$key]['goods_num'] = $value['num'];
            $insert[$key]['goods_total_price'] = $value['goods_total_price'];
            $insert[$key]['create_time'] = time();
            $insert[$key]['sale_id'] = $saleId;
            $insert[$key]['create_id'] = $userInfo['id'];
            $insert[$key]['business_type'] = !empty($value['business_type']) ? $value['business_type'] : 1;
            if(empty($goods_info['engineer_rate'])){
                $commission = 0;
            }else{
                $commission = $goods_info['engineer_rate'] * $value['num'];
            }
            if(empty($goods_info['receiver_rate'])){
                $receiver = 0;
            }else{
                $receiver = $goods_info['receiver_rate'] * $value['num'];
            }
            $insert[$key]['commission'] = $commission;
            $insert[$key]['receiver'] = $receiver;
            //给手牌加金额
            if(!empty($handCardId)){
                //检测最大商品数
                $checkMoney = HandCard::checkMaxGoods($handCardId,$value['product_id'],$value['num']);
                if($checkMoney == false){
                    return ['msg'=>'手牌超出最大商品数','status'=>false];
                }
                $handGrant = Db::name('qt_hand_grant')->where(['hand_card_id'=>$handCardId,'status'=>'2'])->order('id desc')->value('id');
                Db::name('qt_hand_grant')->where(['id'=>$handGrant])->setInc('money',$value['goods_total_price']);
            }
        }
        Db::name('qt_product_order_item')->insertAll($insert);
        $secData = Db::name('qt_product_order_item')->where(['order_id' => $orderId])->select();
        foreach ($secData as $key=>$value){
            //插入订单详情表
            $orderDetailInsert = [
                'store_id'=>$userInfo['store_id'],
                'room_id'=>$orderData['room_id'],
                'engineer_id'=>'',
                'hand_card_id'=>$handCardId,
                'check_out_id'=>'',
                'project_id'=>$value['goods_id'],
                'order_goods_id'=>$value['id'],
                'create_user_id'=>$saleId,
                'order_type'=>'2',
                'create_time'=>time(),
            ];
            Db::name('qt_order_detail')->insert($orderDetailInsert);
        }
        //商品减库存
        foreach ($secData as $key => $value) {
            $goodsProduct = Db::name('qt_goods_product')->where(['goods_id' => $value['goods_id']])->find();
            //有关联库存减库存
            if (!empty($goodsProduct)) {
                $stockData = json_decode($goodsProduct['product_data'],true);
                foreach ($stockData as $k => $v) {
                    //[{"product_id":46,"number":"2","name":"果粒橙","unit":"瓶"}]
                    if (empty($v['product_id'])) continue;

                    $productData = Db::name('qt_product')->where(['id' => $v['product_id']])->find();
                    //dump($productData);die;
                    if($productData != null){
                        $decNumber = bcmul($value['goods_num'], $v['number']);
                        $afterNumber = bcsub($productData['stock'], $decNumber);
                        try {
                            Db::startTrans();
                            //减库存
                            Db::name('qt_product')->where(['id' => $v['product_id']])->setDec('stock', $decNumber);
                            //插入记录
                            $insert = [
                                'product_id' => $v['product_id'],
                                'store_id' => $productData['store_id'],
                                'before' => $productData['stock'],
                                'amount' => $decNumber,
                                'after' => $afterNumber,
                                'type' => '1',
                                'acter' => $userInfo['id'],
                                'source' => '2',
                                'relation_id' => $value['id'],
                                'create_time' => time(),
                            ];
                            Db::name('qt_product_stock_log')->insert($insert);
                            Db::commit();
                        } catch (Exception $exception) {
                            Db::rollback();
                        }
                    }
                }
            }
        }
        return ['msg'=>'添加子订单成功','status'=>true];

    }


    /**
     * 写提成记录表
     *
     * @param $order_id      商品订单ID
     * @param $room_id       房间ID
     */
    public static function saveCommissionLog($order_id, $room_id)
    {

        $goods_item = Db::name('qt_product_order_item')
            ->where('order_id', $order_id)->select();
        if (!empty($goods_item)) {
            $insert = [];
            foreach ($goods_item as $key => $value) {
                $checkFind = Db::name('qt_commission_log')->where(['order_project_id'=>$value['id'],'type'=>'2'])->find();
                if(empty($checkFind)){
                    $userId = 0;
                    $userGroup = Db::name('qt_users')->where(['id'=>$value['sale_id']])->value('group');
                    if($userGroup != null && $userGroup == '1'){
                        $userId = $value['sale_id'];
                    }elseif($userGroup != null && $userGroup == '2'){
                        $cashier_id =  $value['sale_id'];
                    }
                    $insert[] = [
                        'store_id' => $value['store_id'],
                        'cashier_id' => $cashier_id ?? '',
                        'user_id' => $userId,
                        'room_id' => $room_id,
                        'money' => $value['goods_total_price'],
                        'commission' => $value['commission'],
                        'receiver' => $value['receiver'],
                        'product_id' => $value['goods_id'],
                        'type' => '2',
                        'created_time' => time(),
                        'is_pay' => '1',
                        'order_project_id' => $value['id'],
                    ];
                }
            }
            Db::name('qt_commission_log')->insertAll($insert);

        }
    }


    /**
     * 减库存
     */
    public static function stockDec($goodsId, $number, $orderId, $userInfo)
    {
        $goodsProduct = Db::name('qt_goods_product')->where(['goods_id' => $goodsId])->find();
        //有关联库存减库存
        if (!empty($goodsProduct)) {
            $stockData = json_decode($goodsProduct['product_data'],true);
            foreach ($stockData as $k => $v) {
                //[{"product_id":46,"number":"2","name":"果粒橙","unit":"瓶"}]
                $productData = Db::name('qt_product')->where(['id' => $v['product_id']])->find();
                //dump($productData);die;
                if($productData != null){
                    $decNumber = bcmul($number, $v['number']);
                    $afterNumber = bcsub($productData['stock'], $decNumber);
                    try {
                        Db::startTrans();
                        //减库存
                        Db::name('qt_product')->where(['id' => $v['product_id']])->setDec('stock', $decNumber);
                        //插入记录
                        $insert = [
                            'product_id' => $v['product_id'],
                            'store_id' => $productData['store_id'],
                            'before' => $productData['stock'],
                            'amount' => $decNumber,
                            'after' => $afterNumber,
                            'type' => '1',
                            'acter' => $userInfo['id'],
                            'source' => '2',
                            'relation_id' => $orderId,
                            'create_time' => time(),
                        ];
                        Db::name('qt_product_stock_log')->insert($insert);
                        Db::commit();
                    } catch (Exception $exception) {
                        Db::rollback();
                    }
                }
            }
        }
    }


    /**
     * 加库存
     */
    public static function stockInc($goodsId, $number, $orderId, $userInfo)
    {
        $goodsProduct = Db::name('qt_goods_product')->where(['goods_id' => $goodsId])->find();
        //有关联库存减库存
        if (!empty($goodsProduct)) {
            $stockData = json_decode($goodsProduct['product_data'],true);
            foreach ($stockData as $key => $value) {
                //[{"product_id":46,"number":"2","name":"果粒橙","unit":"瓶"}]
                $productData = Db::name('qt_product')->where(['id' => $value['product_id']])->find();
                $incNumber = bcmul($number, $value['number']);
                $afterNumber = bcadd($productData['stock'], $incNumber);
                try {
                    Db::startTrans();
                    //减库存
                    Db::name('qt_product')->where(['id' => $value['product_id']])->setInc('stock', $incNumber);
                    //插入记录
                    $insert = [
                        'product_id' => $value['product_id'],
                        'store_id' => $productData['store_id'],
                        'before' => $productData['stock'],
                        'amount' => $incNumber,
                        'after' => $afterNumber,
                        'type' => '2',
                        'acter' => $userInfo['id'],
                        'source' => '2',
                        'relation_id' => $orderId,
                        'create_time' => time(),
                    ];
                    Db::name('qt_product_stock_log')->insert($insert);
                    Db::commit();
                } catch (Exception $exception) {
                    Db::rollback();
                }
            }
        }
    }


}